<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
      <el-form-item label="客户端名称" prop="name" >
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户端名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="appid" prop="appid" >
        <el-input
          v-model="queryParams.appid"
          placeholder="请输入appid"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wx:client:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx:client:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:client:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wx:client:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="clientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="60"/>
      <el-table-column label="客户端名称" align="center" prop="name" />
      <el-table-column label="appid" align="center" prop="appid" />
      <el-table-column label="微信appid" align="center" prop="wxAppid" />
      <el-table-column label="商户号" align="center" prop="merchantNumber" />
      <el-table-column label="显示控制" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-switch :value="scope.row.isShow == '1'?true:false" @change="showChange(scope.row,scope.$index)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-config"
            @click="handleConfig(scope.row)"
            v-hasPermi="['wx:config:query']"
          >配置</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx:client:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:client:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微信客户端对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户端名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户端名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="appid" prop="appid">
              <el-input v-model="form.appid" placeholder="请输入appid" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="微信appid" prop="wxAppid">
              <el-input v-model="form.wxAppid" placeholder="请输入微信appid" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开发者密码" prop="secret">
              <el-input v-model="form.secret" placeholder="请输入开发者密码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="商户号" prop="merchantNumber">
              <el-input v-model="form.merchantNumber" placeholder="请输入商户号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户密钥" prop="merchantKey">
              <el-input v-model="form.merchantKey" placeholder="请输入商户密钥" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="公钥" prop="publicKey">
          <el-input v-model="form.publicKey" placeholder="请输入公钥" type="textarea"  :autosize="{ minRows: 4,maxRows: 4}" />
        </el-form-item>
        <el-form-item label="私钥" prop="privateKey">
          <el-input v-model="form.privateKey" placeholder="请输入私钥" type="textarea" :autosize="{ minRows: 4,maxRows: 4}"/>
        </el-form-item>

        <el-form-item label="内容加密" prop="decryptKey">
          <el-input v-model="form.decryptKey" placeholder="请输入接口内容加密方式" />
        </el-form-item>

        <el-form-item label="商户证书">
          <el-upload
            class="upload-demo"
            :headers="headers"
            :action="base_url + '/common/upload/file'"
            :on-success="handleSuccess"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            multiple
            :limit="1"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="显示控制">
              <el-switch v-model="form.isShow"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient, exportClient } from "@/api/wx/client";
import { getToken } from "@/utils/auth";

export default {
  name: "Client",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 微信客户端表格数据
      clientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        appid: undefined,
        secret: undefined,
        merchantNumber: undefined,
        merchantKey: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        appid: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      },
      fileList:[],
      base_url: process.env.VUE_APP_BASE_API,
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  created() {
    this.getList();
    this.getDicts("wx_client_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询微信客户端列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        appid: undefined,
        secret: undefined,
        merchantNumber: undefined,
        merchantKey: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        status: '1',
        isShow: true,
        privateKey: undefined,
        publicKey: undefined
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信客户端";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClient(id).then(response => {
        this.form = response.data;
        this.form.isShow = response.data.isShow == '1' ? true : false;
        if (response.data.certificatePath) {
          this.fileList = [{
            url :this.base_url + response.data.certificatePath,
            name:  response.data.certificatePath,
            fileName : response.data.certificatePath
          }];
        }

        console.log(this.form)
        this.open = true;
        this.title = "修改微信客户端";
      });
    },
    handleConfig(row){
      this.$router.push({path:'/ypp/data/configItem',query:{id:row.id}})
    },
    showChange(row,index){
      if (row.isShow == '1'){
        row.isShow = '0';
      } else {
        row.isShow = '1';
      }
      this.clientList[index] = row;

      updateClient(row).then(response => {
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          var f = this.form;
          f.isShow = this.form.isShow ? '1' : '0';

          if (this.fileList.length>0){
            this.form.certificatePath = this.fileList[0].fileName;
          }

          if (this.form.id != undefined) {
            updateClient(f).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {

            addClient(f).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除微信客户端编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delClient(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有微信客户端数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportClient(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleSuccess(file,fileList){
      console.log('上传成功',file,fileList)
      if (typeof fileList == "array" ){
        fileList.filter(e=>{
          e.url = e.response.url;
          e.fileName = e.response.fileName;
        })
        this.fileList = fileList;
      } else {
        fileList.url = fileList.response.url;
        fileList.fileName = fileList.response.fileName;
        this.fileList = [fileList];
      }
    },
    handleExceed(e){
      console.log(e)
      this.$message({
        message: '请先删除已有文件后，再进行上传',
        type: 'error'
      });
    },
    beforeRemove(file, fileList) {
      console.log('移除',file,fileList);
      this.fileList = [];
      this.$message({
        type: 'success',
        message: '移除成功!'
      });
      return ;
    },
  }
};
</script>
